﻿using EvaluationSystem.Models;

using Microsoft.AspNetCore.Mvc;

using System.Diagnostics;
using EvaluationSystem.Dto;

namespace EvaluationSystem.Controllers;

public class HomeController : BaseController<HomeController>
{
    public HomeController(ILogger<HomeController> logger, MyDbContext dbContext) : base(logger, dbContext)
    {
    }

    public IActionResult Index()
    {
        if (GetUserToken<People>(out var val))
        {
            return View();
        }
        else
        {
            return View("Login");
        }
    }

    public IActionResult Login(LoginDto? model)
    {
        if (ReferenceEquals(model, null))
        {
            ViewBag.result = ResultDto.Fail(msg: "参数验证失败");
            return View();
        }

        // 查找账号是否存在
        var count = _dbContext.People.Count(t => t.Number == model.userid || t.Name == model.userid);
        if (count > 0)
        {
            // 获取账号信息
            var p = _dbContext.People
                .FirstOrDefault(t => (t.Number == model.userid || t.Name == model.userid) && t.Password == model.password && t.Career == model.identity);

            if (p == null)
            {
                ViewBag.result = ResultDto.Fail(msg: "账号不存在或密码错误");
            } // 不存在
            else
            {
                // 保存用户信息到session里
                SetUserToken(p);
                var carrer = p.Career;
                // 根据账号类型跳转到不同的页面
                if (carrer == Identity.STUDENT)
                {
                    return RedirectToAction("Index", "Student", null);
                }
                else if (carrer == Identity.TEACHER)
                {
                    return RedirectToAction("Index", "Teacher", null);
                }
                else if (carrer == Identity.LEADER)
                {
                    return RedirectToAction("Index", "Leader", null);
                }
            }
        }
        else
        {
            ViewBag.result = ResultDto.Fail(msg: "账号不存在");
        }
        return View();
    }

    public IActionResult Logout()
    {
        SetUserToken(null);
        return RedirectToAction("Login");
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}